package cn.b.sky.common.utils;

import cn.b.sky.common.exception.InfoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

public class I18NUtil {

    private static final Log LOG = LogFactory.getLog(I18NUtil.class);

    /**
     * 保存资源文件信息
     */
    private static final Map<String, Map<String, String>> PROPERTIES_MAP = new HashMap<String, Map<String, String>>();


    private I18NUtil() {
        // Hide the constructor
    }

    /**
     * 通过语言状态读取对应的资源文件Map对象
     * 
     * @param baseName 资源前缀
     * @param localeString 语言状态
     * @param contryCode 語言
     * @return Map<String, String>对象
     */
    public static Map<String, String> getPropertiesMap(String baseName, String localeString, String contryCode) {
        Locale locale = null;
        if (null == baseName || "".equals(baseName)) {
            throw new InfoException("baseName can not be null!");
        }
        if (null == localeString || "".equals(localeString)) {
            locale = Locale.getDefault();
            LOG.info(locale);
        } else {
            locale = new Locale(localeString, contryCode);
        }
        String key = baseName + "_" + locale.toString();
        if (null == PROPERTIES_MAP.get(key)) {
            Map<String, String> map = new HashMap<String, String>();
            ResourceBundle resourceBundle = null;
            try {
                resourceBundle = ResourceBundle.getBundle("conf/" + baseName, locale);
            } catch (MissingResourceException mre) {
                LOG.error("load properties basename:" + baseName + ",locale:" + locale + "failure", mre);
                throw new MissingResourceException(mre.getMessage(), localeString, mre.getKey());
            }
            Enumeration<String> enums = resourceBundle.getKeys();
            while (enums.hasMoreElements()) {
                String enumKey = enums.nextElement();
                map.put(enumKey, resourceBundle.getString(enumKey));
            }
            PROPERTIES_MAP.put(key, map);
            return map;
        } else {
            return PROPERTIES_MAP.get(key);
        }
    }
}
